package com.study.springboot.factory;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @author huyong
 * @Decription 自定义向头部添加信息
 * @date 2025-03-28 16:08
 */
@Component
public class AddHeaderGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    public AddHeaderGatewayFilterFactory() {
    }

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain) -> {
            // pre-filter 请求进来处理
            long startTime = System.currentTimeMillis();
            System.out.println(config.getName() + "-" + config.getValue() + "开始执行时间:" + startTime);
            exchange.getAttributes().put("startTime", startTime);
            ServerHttpRequest request = exchange.getRequest().mutate().header(config.getName(), config.getValue()).build();
            return chain.filter(exchange.mutate().request(request).build()).then(
                    Mono.fromRunnable(() -> {
                        // post-filter 请求出去处理
                        long endTime = System.currentTimeMillis();
                        long startTimeRequest = exchange.getAttribute("startTime");
                        System.out.println(config.getName() + "-" + config.getValue() + "结束执行时间:" + endTime + "  总计消耗时间:" + (endTime - startTimeRequest));


                    })
            );
        };
    }
}
